package com.thread.example.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Queue;
import java.util.concurrent.*;

public class QueueTask {

    public static void main(String[] args) {
        QueueTask queueTask = new QueueTask();
        queueTask.test();
    }

    public void test() {
        Queue<FutureTask<String>> queue = serviceImpl();
        while (queue.size() != 0) {
            FutureTask<String> poll = queue.poll();
            if (poll == null) {
                queue.add(poll);
            } else {
                try {
                    System.out.println(poll.get());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }


    public Queue<FutureTask<String>> serviceImpl() {
        Queue<FutureTask<String>> queue = new ArrayBlockingQueue<FutureTask<String>>(20);
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 20; i++) {
            Integer index = i;
            FutureTask<String> futureTask = new FutureTask<String>(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(5000);
                    String a = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    System.out.println(String.valueOf(index) + "  impl----  " + a);
                    return a;
                }
            });
            queue.add(futureTask);
            executorService.submit(futureTask);
        }
        executorService.shutdown();
        return queue;
    }


}
